<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Syncer
 *
 * @author aneto
 */
abstract class Syncer {

	private $pks;

	public function __construct(array $pks){
		$this->pks = $pks;
	}

	protected function getPks(){
		return $this->pks;
	}

	public  function sync(){

		$result = '';

		$c = $this->mapData($this->getPks());

		if(!is_array($c))
			throw new Exception('argument should be an array !');

		$tmp_ar = array();

		foreach($c as $index => $val){

			$tmp_ar[] = $val;

			if(($index + 1) % 100 == 0){
				$result .= $this->execute($tmp_ar);
				$tmp_ar = array();
			}

		}

		if(!empty($tmp_ar)){
			$result .= $this->execute($tmp_ar);
			$tmp_ar = array();
		}

		return $result;
		//return $this->isSuccessful($this->execute($c));
	}


	public function getXmlStr(array $items){
		sfProjectConfiguration::getActive()->loadHelpers(array('UtilsXml'));
		
		 $xmlData = array(
			'xml' => array(
				'items' => array(
					'~array:item' => $items,
				)
			)
		);

		$xml = new DOMDocument("1.0", "UTF-8");
		$xml->formatOutput = true;
		xmlAddElementsFromArr($xml, $xml, $xmlData);

//		echo $xml->saveXML();
//		exit;
//
		return $xml->saveXML();
	}


	protected function execute(array $items){
		$request = $this->getRequest($this->getRequestParams($items));
		return $request->send();
	}

	protected function getRequest(array $params){
		return SimpleWebService::getWebService($this->getWebServiceType())->getRequest($this->getRequestType(), $params);
	}

	abstract protected function getRequestType();
	abstract protected function getWebServiceType();
	abstract protected function mapData(array $pks);
	abstract protected function getRequestParams(array $items);
	abstract protected function getRemotePks();

	protected function isSuccessful($response){

		foreach($this->getRemotePks() as $pk){
			if(!substr_count($response, $pk)) return false;
		}
		
		return true;
	}
}

?>
